package com.wang.elm.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wang.elm.entity.User;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class MyCustomSuccessHandler implements AuthenticationSuccessHandler {


    @Resource
    private  JwtTokenUtil jwtTokenUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException {
        CustomUserDetails userDetails = (CustomUserDetails) authentication.getPrincipal();
        User user = userDetails.getUser();
        response.setContentType("application/json;charset=UTF-8");

        String token = jwtTokenUtil.generateToken(authentication.getName());
        user.setToken(token);
        System.out.println();
        new ObjectMapper().writeValue(response.getWriter(), user);
    }
}
